﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.Compilation;
using UnityEngine;
using UnityEngine.AddressableAssets;

public class XPackageWindow : EditorWindow
{
    [MenuItem("XAddresables/Package")]
   private static void Init()
    {
        XPackageWindow window = EditorWindow.GetWindow<XPackageWindow>();
        window._buildPath = XBuildContentEditor.buildPath;
        window.textAssetVersion = AssetDatabase.LoadAssetAtPath<TextAsset>(XBuildContentEditor.resUpdatePath + "/Asset/TextAsset/" + XRes.N("Version", XResType.TextAsset) + ".txt");
    }

    [MenuItem("XAddresables/修复Package打不开")]
    private static void UnInit()
    {
        XPackageWindow window = EditorWindow.GetWindow<XPackageWindow>();
        window.Close();
    }

    private string _buildPath;
    private bool _isTestDownloadInEditor;
    public TextAsset textAssetVersion;

    private void OnGUI()
    {
        textAssetVersion = EditorGUILayout.ObjectField("资源版本路径:", textAssetVersion, typeof(TextAsset), false) as TextAsset;
        EditorGUILayout.TextField("热更动态变化的catalogPath:", XDownload.catalogPath);

        EditorGUILayout.TextField("BuildPath(catalog+基础bundle）:", _buildPath);
        EditorGUILayout.TextField("差异BuildPath(增量bundle):", XBuildContentEditor.buildCotentUpdatePath);
        GUILayout.Label("(1)校验差异:");
        GUILayout.Label("           (1.1)点击Menu打开Group窗口：Window/Asset Management/Addressables/Groups");
        GUILayout.Label("           (1.2)点击Groups窗口的Menu：Tools/Check fro Content Update Restrictions");
        if (GUILayout.Button("(2)加上热更标签"))
        {
            XBuildContentEditor.HandleContentGroup();
            Debug.Log("(2)加上热更标签");
        }
        GUILayout.Label("(3)Build差异");
        GUILayout.Label("           (3.1)点击Groups窗口的Menu：Build/Update a Previous Build");
        //if (GUILayout.Button("Build差异")) {
        //    BuildContentUpdate();
        //}

        #region Download In Editor
        _isTestDownloadInEditor = GUILayout.Toggle(_isTestDownloadInEditor, "Download In Editor");
        if (_isTestDownloadInEditor)
        {
            GUILayout.Label("----Start----");
            EditorGUILayout.TextField("备份Catalog/Bundle-Path:", XBuildContentEditor.backupPathCatalogAndBundle);
            GUILayout.Label("中的bundle文件拷贝过去BuildPath(" +
                _buildPath+")");
            if (GUILayout.Button("Restore bundle"))
            {
                RestoreBundle();
            }

            GUILayout.Label("热更动态变化的catalogPath恢复到最初版本");
            if (GUILayout.Button("Restore catalog"))
            {
                RestoreCatalog();
            }

            if (GUILayout.Button("ScriptCompile强制编译工程，测试使用（正常情况不用管此按钮）"))
            {
                CompilationPipeline.RequestScriptCompilation();
            }
            GUILayout.Label("----End----");
        }
        #endregion

        if (GUILayout.Button("(4)从BuildPath拷贝Catalog到 差异BuildPath"))
        {
            CopyCatalog2CotentUpdatePath();
            Debug.Log("(4)从BuildPath拷贝Catalog到 差异BuildPath");
        }

        GUILayout.Label("未完成：更新Catalog的时间，也要显示进度条。（项目资源大了，可能很久）");
        GUILayout.Label("未完成：更新到一半，退出游戏");
        GUILayout.Label("未完成：白名单下载");
    }


    /*
    public static void BuildContentUpdate()
    {
        //生成 差异组bundle
        var path = UnityEditor.AddressableAssets.Build.ContentUpdateScript.GetContentStateDataPath(true);
        if (!string.IsNullOrEmpty(path))
        {
            UnityEditor.AddressableAssets.Build.ContentUpdateScript.BuildContentUpdate(UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings, path);
        }
        else
        {
            Debug.LogError("Can not find path:" + path);
        }
    }
    */
    private void RestoreBundle()
    {
        var backupPathBundle = XBuildContentEditor.backupPathCatalogAndBundle;
        var paths = Directory.GetFiles(backupPathBundle, "*.bundle");
        foreach (var path in paths)
        {
            string toPath = Path.Combine(_buildPath, Path.GetFileName(path));
            Debug.Log("恢复：" + path + " 到 " + toPath);
            File.Copy(path, toPath);
        }
    }

    private void RestoreCatalog()
    {
        var backupPathCatalog = XBuildContentEditor.backupPathCatalogAndBundle;
        var paths1 = Directory.GetFiles(backupPathCatalog, "*.hash");
        var paths2 = Directory.GetFiles(backupPathCatalog, "*.json");
        List<string> paths = new List<string>();
        paths.AddRange(paths1);
        paths.AddRange(paths2);

        var catalogPath = XDownload.catalogPath;
        if (!Directory.Exists(catalogPath))
            Directory.CreateDirectory(catalogPath);
        foreach (var path in paths)
        {
            string toPath = Path.Combine(catalogPath, Path.GetFileName(path));
            Debug.Log("拷贝：" + path + " 到 " + toPath);
            File.Copy(path, toPath, true);
        }
    }

    private void CopyCatalog2CotentUpdatePath()
    {
        //遍历文件
        var sourcePath = XBuildContentEditor.buildPath;
        var paths1 = Directory.GetFiles(sourcePath, "*.hash");
        var paths2 = Directory.GetFiles(sourcePath, "*.json");
        List<string> paths = new List<string>();
        paths.AddRange(paths1);
        paths.AddRange(paths2);

        //开始备份
        var contentUpdatePath = XBuildContentEditor.buildCotentUpdatePath;
        foreach (var path in paths)
        {
            string toPath = Path.Combine(contentUpdatePath, Path.GetFileName(path));
            Debug.Log("copy：" + path + " 到 " + toPath);
            File.Copy(path, toPath, true);
        }
    }
}
